//
//  GBNicknameViewController.m
//  PublicSentimentMonitorSystem
//
//  Created by 郭斌 on 15/11/7.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "GBNicknameViewController.h"
#import "UniversialTextfield.h"
#import "GBPopUpView.h"
#import "GBMonitorTableview2.h"
#import "AFNetworking.h"
#import "SVProgressHUD.h"

@interface GBNicknameViewController ()<UITextFieldDelegate, ShowTheSelectResult>
{
    UniversialTextfield *nicknameTextfield; //输入昵称的textfield
    UIButton *searchBtn; //查询按钮
    UITapGestureRecognizer *tapGestureClick; //点击手势
    UILabel *hintLabel; //提示信息的label
    UIView *view11;
    NSMutableArray *nicknameArray; //用户选择的昵称
    NSMutableArray *nicknameIdArray; //用户选择昵称的id
    GBMonitorTableview2 *tableV; //显示选择的结果
    NSMutableArray *copyNicknameArray;
    NSMutableArray *copyNicknameIdArray;
}
@end

@implementation GBNicknameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = WQColor(247, 249, 250);
    copyNicknameArray = [NSMutableArray array];
    copyNicknameIdArray = [NSMutableArray array];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newData:) name:@"NewArray" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newData2222:) name:@"NewArray2222" object:nil];
    
    //初始化点击手势，以判断是否点击的是除了uitextfield之外的地方
    [self createTapGesture];
    
    nicknameTextfield = [[UniversialTextfield alloc] initWithFrame:CGRectMake(0, 20, screenW, 35)];
    nicknameTextfield.backgroundColor = [UIColor whiteColor];
    nicknameTextfield.placeholder = @"请输入昵称";
    nicknameTextfield.layer.borderColor = [UIColor lightGrayColor].CGColor;
    //键盘类型
    nicknameTextfield.keyboardType = UIKeyboardTypeDefault;
    //返回按钮类型
    nicknameTextfield.returnKeyType = UIReturnKeyDone;
    //改变输入框起始位置
    [self setTextFieldLeftPadding:nicknameTextfield forWidth:10];
    nicknameTextfield.delegate = self;
    [self.view addSubview:nicknameTextfield];
    
    searchBtn = [UIButton buttonWithType:0];
    //searchBtn.backgroundColor = KDColor;
    searchBtn.frame = CGRectMake(screenW - 40, 20, 40, 35);
    [searchBtn setImage:[UIImage imageNamed:@"默认添加"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchBtn];
    
    view11 = [[UIView alloc] initWithFrame:CGRectMake(0, 55, screenW, 30)];
    
    hintLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, screenW, 30)];
    hintLabel.textColor = [UIColor lightGrayColor];
    hintLabel.font = [UIFont systemFontOfSize:12];
    hintLabel.text = @"请输入昵称";
    [view11 addSubview:hintLabel];
    [self.view addSubview:view11];
    
    //创建tablevew
    [self createTable];
    // Do any additional setup after loading the view.
}

#pragma mark - 创建tablevew
-(void)createTable
{
    if(tableV == nil)
    {
        if(_dataArray == nil || _dataArray.count == 0)
        {
            tableV = [[GBMonitorTableview2 alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        }
        else
        {
            tableV = [[GBMonitorTableview2 alloc] initWithFrame:CGRectMake(0, 90, screenW, 200)];
            copyNicknameArray = [NSMutableArray arrayWithArray:_dataArray];
            copyNicknameIdArray = [NSMutableArray arrayWithArray:_dataIdArray];
            tableV.dataArray = [NSMutableArray arrayWithArray:_dataArray];
            tableV.dataIdArray = [NSMutableArray arrayWithArray:_dataIdArray];
        }
        [self.view addSubview:tableV];
    }
}

#pragma mark - 删除按钮，接收新的数据(弹出界面的数据)
-(void)newData:(NSNotification *)note
{
    NSDictionary *user = [note userInfo];
    NSMutableArray *dataArr = [user objectForKey:@"deleteArray"];
    NSMutableArray *dataIDArr = [user objectForKey:@"deleteIDArray"];
   
    nicknameArray = [NSMutableArray arrayWithArray:dataArr];
    nicknameIdArray = [NSMutableArray arrayWithArray:dataIDArr];
    //NSLog(@"#####1  %@", dataArr);
    //NSLog(@"#####2  %@", dataIDArr);
}

#pragma mark - 删除按钮，接收新的数据(昵称)
-(void)newData2222:(NSNotification *)note
{
    NSDictionary *user = [note userInfo];
    NSMutableArray *dataArr = [user objectForKey:@"deleteArray"];
    NSMutableArray *dataIdArr = [user objectForKey:@"deleteIDArray"];
    
    copyNicknameArray = [NSMutableArray arrayWithArray:dataArr];
    copyNicknameIdArray = [NSMutableArray arrayWithArray:dataIdArr];
    //NSLog(@"#####3  %@", dataArr);
    //NSLog(@"#####4  %@", dataIdArr);
}

#pragma mark - 显示选择的结果
-(void)showTheSelectResult
{
    for(int i = (int)nicknameArray.count - 1; i >= 0; i--)
    {
        [copyNicknameArray insertObject:nicknameArray[i] atIndex:0];
        [copyNicknameIdArray insertObject:nicknameIdArray[i] atIndex:0];
    }
    
    if(_dataArray == nil || _dataArray.count == 0)
    {
        tableV.frame = CGRectMake(0, 90, screenW, 200);
    }
    tableV.dataArray = [NSMutableArray arrayWithArray:copyNicknameArray];
    tableV.dataIdArray = [NSMutableArray arrayWithArray:copyNicknameIdArray];
    [tableV reloadData];
}

#pragma mark - 昵称中的查询操作
-(void)searchAction
{
    [SVProgressHUD showProgress:-1 status:@"正在请求" maskType:SVProgressHUDMaskTypeGradient];
    [searchBtn setEnabled:NO];
    [nicknameTextfield resignFirstResponder];
    if(nicknameTextfield.text.length != 0)
    {
        //根据输入的text请求网络
        KDAccount *account = [KDAccountTool account];
        NSString *inputS = [NSString stringWithFormat:@"%@",nicknameTextfield.text];
        inputS = [inputS stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
        NSString *saveUrl = [NSString stringWithFormat:@"%@%@%@%@%@", ServerActionAddr, @"&method=inquireTheNickname&token=",account.tokens,@"&name=",inputS];
        //NSLog(@"%@",saveUrl);
        //请求数据
        NSURLRequest *httpReq = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:saveUrl]];
        
        AFHTTPRequestOperation *reqOper = [[AFHTTPRequestOperation alloc] initWithRequest:httpReq];
        [reqOper setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *op,id success){
            NSHTTPURLResponse *response = [op response];
            NSInteger code = [response statusCode];
            if (code == 200)
            {
                NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[op responseData] options:NSJSONReadingMutableContainers error:nil];
                if([jsonDict[@"status"] isEqualToString:@"ok"])
                {
                    NSMutableArray *info = jsonDict[@"info"];
                    NSMutableArray *arra = [NSMutableArray array];
                    NSMutableArray *arraID = [NSMutableArray array];
                    
                    if ([jsonDict[@"info"] isKindOfClass:[NSNull class]])
                    {
                        [SVProgressHUD showErrorWithStatus:@"没有新数据" maskType:SVProgressHUDMaskTypeGradient];
                    }
                    else
                    {
                        for(NSDictionary *dic in info)
                        {
                            [arra addObject:dic[@"authorName"]];
                            int num = [dic[@"id"] intValue];
                            [arraID addObject:[NSString stringWithFormat:@"%d", num]];
                        }
                    
                        //弹出选择框
                        GBPopUpView *popView = [[GBPopUpView alloc] initWithFrame:CGRectMake(screenW / 2.0 - 120, 100, 240, 320)];
                        
                        NSDictionary *userInfo11b = [[NSDictionary alloc] initWithObjectsAndKeys:arra, @"dataArrayNickname", arraID, @"dataArrayNicknameID",nil];
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"DataArrayNickname" object:nil userInfo:userInfo11b];
                        
                        popView.delegateShow = self;
                        [self.view.window addSubview:popView];
                    }
                    [SVProgressHUD dismiss];
                    //设置searchBtn可点击
                    [searchBtn setEnabled:YES];
                }
                //账号在别处登录
                else if([jsonDict[@"status"] isEqualToString:@"notlogin"])
                {
                    [SVProgressHUD showErrorWithStatus:@"该账号已在其他地方登陆" maskType:SVProgressHUDMaskTypeGradient];
                    
                    KDNewfeatureController *login = [[KDNewfeatureController alloc] init];
                    //跳转到登陆界面
                    //设置切换风格
                    login.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
                    //2.切换控制器
                    [self presentViewController:login animated:YES completion:nil];
                    [SVProgressHUD dismiss];
                }
                //查询失败
                else if ([jsonDict[@"status"] isEqualToString:@"err"])
                {
                    [SVProgressHUD showErrorWithStatus:@"查询失败" maskType:SVProgressHUDMaskTypeGradient];
                    [searchBtn setEnabled:YES];
                    [SVProgressHUD dismiss];
                }
            }
        } failure:^(AFHTTPRequestOperation *op, NSError *error) {
            if (error) {
                //NSLog(@"req error %@",error);
                [SVProgressHUD showErrorWithStatus:@"网络请求失败" maskType:SVProgressHUDMaskTypeGradient];
                [searchBtn setEnabled:YES];
                [SVProgressHUD dismiss];
            }
        }];
        [reqOper start];
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"输入内容不能为空" maskType:SVProgressHUDMaskTypeGradient];
        [searchBtn setEnabled:YES];
        [SVProgressHUD dismiss];
    }
}

#pragma mark - 弹出的对话框内容
- (void)timerFireMethod:(NSTimer*)theTimer//弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert = nil;
}

#pragma mark - 初始化点击手势，以判断是否点击的是除了uitextfield之外的地方
-(void)createTapGesture
{
    //开启交互
    self.view.userInteractionEnabled = YES;
    tapGestureClick = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TapClick)];
    [self.view addGestureRecognizer:tapGestureClick];
}

#pragma mark - 点击除了uitextfield之外的地方，键盘消失
-(void)TapClick
{
    if(nicknameTextfield.text.length == 0)
    {
        nicknameTextfield.placeholder = @"请输入昵称";
    }
    [nicknameTextfield resignFirstResponder];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [nicknameTextfield resignFirstResponder];
    return YES;
}

-(void)setTextFieldLeftPadding:(UITextField *)textField forWidth:(CGFloat)leftWidth
{
    CGRect frame = textField.frame;
    frame.size.width = leftWidth;
    UIView *leftview = [[UIView alloc] initWithFrame:frame];
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.leftView = leftview;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [self.delecateNickname nicknameReturnResult:copyNicknameArray and:copyNicknameIdArray];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
